<script setup lang="ts">
import { computed, onMounted, ref, watch } from "vue";
import {
  authRoleMenu,
  selectMenuList,
  selectSysRoleList,
} from "@/api/system.ts";
import { ElMessage } from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object,
    default: null,
  },
});

const emit = defineEmits(["update:visible", "update:data", "submit"]);
const treeData = ref([]);
const defaultCheckedKeys = ref([]);
const elTreeRef = ref();
const submitLoading = ref<boolean>(false);
const defaultProps = {
  children: "children",
  label: "menuName",
};

const dialogVisible = computed({
  get() {
    return props.visible;
  },

  set(visible: boolean) {
    emit("update:visible", visible);
  },
});

function closeDialog() {
  emit("update:visible", false);
  emit("update:data", null);
}

async function submitForm() {
  const checkedNodes: any[] = elTreeRef.value.getCheckedNodes();

  const set = new Set();

  checkedNodes?.forEach((menu) => {
    set.add(menu?.id);
    if (Number(menu?.parentId)) {
      set.add(menu?.parentId);
    }
  });

  const checkedIds = [...set]?.map((menu) => {
    return {
      sysMenuId: menu,
    };
  });

  submitLoading.value = true;

  const { success, msg } = await authRoleMenu({
    roleId: props.data?.id,
    sysRoleMenus: checkedIds,
  });
  submitLoading.value = false;
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  closeDialog();
  emit("submit");
}

async function getMenuList() {
  const { data } = await selectMenuList();
  treeData.value = data || [];
}

async function getCheckedMenuList(id: string) {
  const { data } = await selectSysRoleList(id);
  defaultCheckedKeys.value = data;
}

onMounted(async () => {
  await getMenuList();
});

watch(
  () => props.visible,
  () => {
    if (props.visible) {
      getCheckedMenuList(props.data?.id);
    } else {
      elTreeRef.value.setCheckedKeys([]);
    }
  },
);
</script>

<template>
  <el-dialog
    @close="closeDialog"
    v-model="dialogVisible"
    title="授权"
    width="30%"
  >
    <el-tree
      node-key="id"
      show-checkbox
      check-strictly
      :data="treeData"
      :props="defaultProps"
      :default-checked-keys="defaultCheckedKeys"
      ref="elTreeRef"
    />
    <div class="footer">
      <el-button @click="submitForm" type="primary" :loading="submitLoading">
        保存
      </el-button>
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.footer {
  width: 100%;
  text-align: center;
  margin-top: 50px;
}
</style>
